package com.yuexun.beilunpatient.ui.registration.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;

import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseEntity;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.registration.adapter.RegistrationDocAdapter;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentDocBean;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentDocData;
import com.yuexun.beilunpatient.ui.registration.model.impl.RegistrationModel;
import com.yuexun.beilunpatient.ui.registration.presenter.impl.AppointmentDocListPresenter;
import com.yuexun.beilunpatient.ui.registration.ui.view.IAppointmentDocListView;
import com.yuexun.beilunpatient.utils.DateUtil;
import com.yuexun.beilunpatient.widget.LoadingDialog;
import com.yuexun.beilunpatient.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshList;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/10/29.
 */
public class Act_Registration_Doctor extends BaseKJActivity implements IAppointmentDocListView {
    @Bind(R.id.iv_pre)
    ImageView iv_pre;
    @Bind(R.id.iv_next)
    ImageView iv_next;
    @Bind(R.id.radio01)
    RadioButton radio01;
    @Bind(R.id.radio02)
    RadioButton radio02;
    @Bind(R.id.radio03)
    RadioButton radio03;
    @Bind(R.id.radio04)
    RadioButton radio04;
    @Bind(R.id.radio05)
    RadioButton radio05;
    @Bind(R.id.content_list)
    PullToRefreshList contentList;

    RadioButton[] tv_radioButton;
    //全部日期
    List<Date> tv_date = new ArrayList<>();
    List<String> tv_week = new ArrayList<>();
    List<String> tv_isData = new ArrayList<>();
    //显示日期
    List<Date> tv_date_show = new ArrayList<>();
    List<String> tv_week_show = new ArrayList<>();
    //显示日期yyyy-MM-dd
    List<String> tv_datatime_show = new ArrayList<>();
    List<String> tv_isData_show = new ArrayList<>();
    String startDate = "";
    int index = 0;
    //选中的日期
    String selectDate;
    //第几天获取数据
    int position = 0;
    // 创建集合对象
    Map<String, List<AppointmentDocData>> map = new HashMap<String, List<AppointmentDocData>>();

    ListView listView;
    RegistrationDocAdapter adapter;
    private int nowpage = 1;
    private int pagesize = 100;
    AppointmentDocListPresenter docListPresenter;
    List<AppointmentDocData> datas = new ArrayList<>();
    LoadingDialog loadingDialog;

    String type = "doc";

    @Override
    public void setRootView() {
        setContentView(R.layout.act_registration_doctor);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        docListPresenter = new AppointmentDocListPresenter(new RegistrationModel(), this);
        tv_radioButton = new RadioButton[]{radio01, radio02, radio03, radio04, radio05};

        for (int i = 0; i < 15; i++) {
            Date date = DateUtil.getDayAfter(new Date(), i + 1);
            String week = DateUtil.getDayOfWeek(new Date(), i + 1);
            tv_date.add(date);
            tv_week.add(week);
        }

        for (int i = 0; i < 5; i++) {
            tv_date_show.add(tv_date.get(i));
            tv_week_show.add(tv_week.get(i));
            tv_radioButton[i].setText(new SimpleDateFormat("dd日").format(tv_date.get(i)) + "\n" + tv_week.get(i));
            tv_datatime_show.add(new SimpleDateFormat("yyyy-MM-dd").format(tv_date.get(i)));
        }

        iv_pre.setEnabled(false);

        startDate = new SimpleDateFormat("yyyy-MM-dd").format(tv_date_show.get(0));
        selectDate = startDate;

        loadingDialog = new LoadingDialog(aty);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();
        position = 0;
        ApiGetData();

        initList();
    }

    private void ApiGetData(){
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", pagesize + "");
        params.put("pageIndex", nowpage + "");
        params.put("scheduleEnddate", startDate);
        params.put("scheduleBegdate", startDate);
        params.put("resourcesType", "Y");
        if(getIntent().getExtras().getString("type").equals("2")){
            params.put("zxksdm", getIntent().getExtras().getString("depId"));//中心科室代码
            params.put("departmentId", "");
        }else{
            params.put("zxksdm", "");//中心科室代码
            params.put("departmentId", getIntent().getExtras().getString("depId"));
        }
//        params.put("doctorName", "");
        params.put("hospitalId", getIntent().getExtras().getString("hosId"));
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        docListPresenter.getAppointmentDocList(params);
    }

    /**
     * 初始化列表
     */
    private void initList() {

        listView = contentList.getRefreshView();
        listView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        contentList.setPullRefreshEnabled(false);
        contentList.setPullLoadEnabled(false);
        ((FooterLoadingLayout) contentList.getFooterLoadingLayout()).setNoMoreDataText("无更多数据");

        adapter = new RegistrationDocAdapter(listView, datas, R.layout.item_registrationdoc);
        listView.setAdapter(adapter);

        contentList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                type = "doc";
                nowpage = 1;
                ApiGetData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                nowpage = nowpage + 1;
                ApiGetData();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                AppointmentDocData item = (AppointmentDocData) adapterView.getItemAtPosition(i);
                Bundle bundle = new Bundle();
                bundle.putString("doctorId", item.getDoctor_id());
                bundle.putString("depId", getIntent().getExtras().getString("depId"));
                bundle.putString("hosId", getIntent().getExtras().getString("hosId"));
                bundle.putString("selectDate", selectDate);
                bundle.putString("type", type);
                Intent intent = new Intent(aty, Act_Registration_DocInfo.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.title_back, R.id.iv_pre, R.id.iv_next, R.id.radio01, R.id.radio02, R.id.radio03, R.id.radio04, R.id.radio05})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.iv_pre:
                tv_date_show.clear();
                tv_week_show.clear();
                tv_datatime_show.clear();
                if(index == 1){
                    iv_pre.setImageResource(R.drawable.ic_pre_no);
                    iv_pre.setEnabled(false);
                    index = 0;
                    for (int i = 0; i < 5; i++) {
                        tv_date_show.add(tv_date.get(i));
                        tv_week_show.add(tv_week.get(i));
                        tv_datatime_show.add(new SimpleDateFormat("yyyy-MM-dd").format(tv_date.get(i)));
                    }
                } else if(index == 2){
                    iv_next.setImageResource(R.drawable.ic_next);
                    iv_next.setEnabled(true);
                    index = 1;
                    for (int i = 5; i < 10; i++) {
                        tv_date_show.add(tv_date.get(i));
                        tv_week_show.add(tv_week.get(i));
                        tv_datatime_show.add(new SimpleDateFormat("yyyy-MM-dd").format(tv_date.get(i)));
                    }
                }
                tv_radioButton[0].setChecked(true);
                startDate = tv_datatime_show.get(0);
                selectDate = startDate;
                refreshTitleView();
                refreshDataView(tv_datatime_show.get(0));
                break;
            case R.id.iv_next:
                tv_date_show.clear();
                tv_week_show.clear();
                tv_datatime_show.clear();
                if(index == 0){
                    iv_pre.setImageResource(R.drawable.ic_pre);
                    iv_pre.setEnabled(true);
                    index = 1;
                    for (int i = 5; i < 10; i++) {
                        tv_date_show.add(tv_date.get(i));
                        tv_week_show.add(tv_week.get(i));
                        tv_datatime_show.add(new SimpleDateFormat("yyyy-MM-dd").format(tv_date.get(i)));
                    }
                } else if(index == 1){
                    iv_next.setImageResource(R.drawable.ic_next_no);
                    iv_next.setEnabled(false);
                    index = 2;
                    for (int i = 10; i < 15; i++) {
                        tv_date_show.add(tv_date.get(i));
                        tv_week_show.add(tv_week.get(i));
                        tv_datatime_show.add(new SimpleDateFormat("yyyy-MM-dd").format(tv_date.get(i)));
                    }
                }
                tv_radioButton[0].setChecked(true);
                position = 0;
                startDate = tv_datatime_show.get(0);
                selectDate = startDate;
                boolean flag=map.containsKey(startDate);
                if(!flag){
                    for (int i = 0; i < 5; i++) {
                        tv_radioButton[i].setText(new SimpleDateFormat("dd日").format(tv_date_show.get(i)) + "\n" + tv_week_show.get(i));
                    }
                    loadingDialog.show();
                    ApiGetData();
                }else{
                    refreshTitleView();
                    refreshDataView(tv_datatime_show.get(0));
                }
                break;
            case R.id.radio01:
                startDate = tv_datatime_show.get(0);
                if(!selectDate.equals(startDate)){
                    selectDate = startDate;
                    refreshDataView(startDate);
                }
                break;
            case R.id.radio02:
                startDate = tv_datatime_show.get(1);
                if(!selectDate.equals(startDate)){
                    selectDate = startDate;
                    refreshDataView(startDate);
                }
                break;
            case R.id.radio03:
                startDate = tv_datatime_show.get(2);
                if(!selectDate.equals(startDate)){
                    selectDate = startDate;
                    refreshDataView(startDate);
                }
                break;
            case R.id.radio04:
                startDate = tv_datatime_show.get(3);
                if(!selectDate.equals(startDate)){
                    selectDate = startDate;
                    refreshDataView(startDate);
                }
                break;
            case R.id.radio05:
                startDate = tv_datatime_show.get(4);
                if(!selectDate.equals(startDate)){
                    selectDate = startDate;
                    refreshDataView(startDate);
                }
                break;
        }
    }

    //刷新列表
    private void refreshDataView(String key){
        for (Map.Entry<String, List<AppointmentDocData>> entry : map.entrySet()) {
            if(entry.getKey().equals(key)){
                datas.clear();
                datas.addAll(entry.getValue());
                if(datas.size() == 1 && datas.get(0).getDoctor_name().isEmpty()){
                    type = "dep";
                }else{
                    type = "doc";
                }
                adapter.refresh(datas);
            }
        }
    }

    //刷新日期
    private void refreshTitleView(){
        for (int i = 0; i < 5; i++) {
            String str2 = new SimpleDateFormat("dd日").format(tv_date_show.get(i)) + "<br>" + tv_week_show.get(i)+"<font color='#FF0000'><small>无</small></font>";
            tv_radioButton[i].setText(Html.fromHtml(str2));
            String key = tv_datatime_show.get(i);
            for (Map.Entry<String, List<AppointmentDocData>> entry : map.entrySet()) {
                if(entry.getKey().equals(key)){
                    if(entry.getValue().size() > 0){
                        tv_radioButton[i].setText(new SimpleDateFormat("dd日").format(tv_date_show.get(i)) + "\n" + tv_week_show.get(i));
                    }
                }
            }

        }
    }

    @Override
    public void getAppointmentDocList(BaseEntity<AppointmentDocBean> baseEntity) {
        if (baseEntity.getStatus().equals("200")) {
            List<AppointmentDocData> value = baseEntity.getDatas().get(0).getList();
            map.put(startDate, value);
            if(selectDate.equals(startDate)){
                datas.clear();
                datas.addAll(baseEntity.getDatas().get(0).getList());
                if(datas.size() == 1 && datas.get(0).getDoctor_name().isEmpty()){
                    type = "dep";
                }
                adapter.refresh(datas);
            }

        }else {
            ViewInject.toast(baseEntity.getMessage());
        }

        if(position == 4){
            loadingDialog.dismiss();
            refreshTitleView();
        }

        if(position < 4){
            position++;
            startDate = tv_datatime_show.get(position);
            ApiGetData();
        }
    }

}
